package com.xky.ui.module.inventorManagement;

import com.xky.pojo.Inventory;
import com.xky.ui.main.MainView;
import com.xky.ui.module.inventorManagement.select.SelectInvenTory;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class InvenToryInfo {

    private static JTable inventoryTable;

    /**
     * 显示库存信息页面
     */
    public static void showInventoryInfoPage() {
        // 创建库存信息面板
        JPanel inventoryInfoPanel = InvenToryMassage.createInvenToryPanel(InvenToryInfo::refreshInventoryData);

        // 获取表格组件
        Component[] components = ((JScrollPane)inventoryInfoPanel.getComponent(1)).getViewport().getComponents();
        if (components.length > 0 && components[0] instanceof JTable) {
            inventoryTable = (JTable) components[0];
        }

        // 更新右侧面板
        MainView.rightPanel.removeAll();
        MainView.rightPanel.add(inventoryInfoPanel, BorderLayout.CENTER);
        MainView.rightPanel.revalidate();
        MainView.rightPanel.repaint();

        // 注册刷新操作
        MainView.registerRefreshAction("库存信息", InvenToryInfo::refreshInventoryData);

        // 立即刷新一次
        refreshInventoryData();
    }

    /**
     * 刷新库存数据
     */
    static void refreshInventoryData() {
        new SwingWorker<List<Inventory>, Void>() {
            @Override
            protected List<Inventory> doInBackground() {
                DefaultTableModel model = (DefaultTableModel) inventoryTable.getModel();
                model.setRowCount(0);
                
                // 获取所有库存数据
                return SelectInvenTory.selectAllInventory();
            }

            @Override
            protected void done() {
                try {
                    List<Inventory> inventory = get();
                    if (inventoryTable != null) {
                        InvenToryMassage.updateTableData(inventoryTable, inventory);
                        MainView.rightPanel.repaint();
                    }
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                            "刷新失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        }.execute();
    }

} 